package com.yc.springmvc.controller;

import com.yc.springmvc.bean.Person;
import com.yc.springmvc.bean.Result;
import com.yc.springmvc.biz.BizException;
import com.yc.springmvc.biz.UserBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UserDo {

    /**
     * 进行参数验证
     * @param p
     * @param errors  验证结果对象
     * @return
     */
    @RequestMapping("/reg1")
    public Result reg1(Person p, Errors errors){
        if (errors.hasErrors()){
            return new Result(0,"字段验证错误",errors.getAllErrors());
        }
        return new Result(1,"注册成功",p);
    }

    @RequestMapping("/reg")
    public Result reg(@Valid Person p, Errors errors){
        if (errors.hasErrors()){
            return new Result(0,"字段验证错误",errors.getAllErrors());
        }
        return new Result(1,"注册成功",p);
    }



    @PostMapping("uploadfile")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        //获取文件名
        String filename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString()+"."+
                //后缀
                filename.substring(filename.lastIndexOf(".")+1);
        File fileObject = new File("D:\\java\\git\\git local\\s3\\SpringMvc\\src\\main\\webapp",newFileName);
        file.transferTo(fileObject);
        //D:\java\git\git local\s3\SpringMvc\src\main\webapp  映射为 => /upload/a.jpg
        return new Result(1,"文件上传成功","upload/" + newFileName);
    }

    @Autowired
    UserBiz userBiz;

    @PostMapping("login")
    public Result login(@Valid Person person,Errors errors,HttpSession session) throws BizException {
        if (errors.hasFieldErrors("name") || errors.hasFieldErrors("pwd")){
            return new Result(0,"字段验证错误",errors.getAllErrors());
        }
        /*try {

        } catch (BizException e) {
            return new Result(0,e.getMessage(),null);
        }*/
        Person loginedUser = userBiz.login(person);
        session.setAttribute("loginedUser",loginedUser);
        return new Result(1,"登陆成功",loginedUser);
    }


    //异常拦截  只当当前类有效
   /* @ExceptionHandler
    public Result handleBizException(BizException e){
        return new Result(0,e.getMessage(),null);
    }*/
}
